package tech.summerly.weather.component.viewmodel

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MediatorLiveData
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import tech.summerly.weather.data.local.RegionDataBase
import tech.summerly.weather.model.UserRegion

class UserRegionViewModel : ViewModel() {


    private val userRegionDao = RegionDataBase.INSTANCE.userRegionDao()

    private val observableUserRegions: MediatorLiveData<List<UserRegion>> = MediatorLiveData()

    init {
        observableUserRegions.addSource(userRegionDao.getTotalUserRegions()) { t: List<UserRegion>? ->
            if (t != null && t.isNotEmpty()) {

                val newList = ArrayList<UserRegion>()
                val header = t.find { it.previous == UserRegion.ID_NONE }!!
                newList.add(header)
                var next = header.next
                while (next != UserRegion.ID_NONE) {
                    val find = t.find { it.id == next }!!
                    newList.add(find)
                    next = find.next
                }
                observableUserRegions.value = newList
            } else {
                observableUserRegions.value = t
            }
        }
    }

    val regionList: LiveData<List<UserRegion>> = observableUserRegions

    fun add(userRegion: UserRegion) {
        userRegionDao.insertUserRegion(userRegion)
    }

    fun remove(userRegion: UserRegion) {
        userRegionDao.removeUserRegion(userRegion)
    }

    fun move(userRegion: UserRegion, previous: UserRegion?, next: UserRegion?) {
        userRegionDao.moveUserRegion(userRegion,
                previous = previous?.id ?: UserRegion.ID_NONE,
                next = next?.id ?: UserRegion.ID_NONE)
    }


    companion object : ViewModelProvider.Factory {

        private var userRegionViewModel: UserRegionViewModel? = null

        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            @Suppress("UNCHECKED_CAST")
            return (userRegionViewModel ?: synchronized(this) {
                userRegionViewModel ?: UserRegionViewModel().also { userRegionViewModel = it }
            }) as T
        }

    }

}